package org.hejw.rpc.client;

import lombok.Getter;
import lombok.Setter;
import org.hejw.rpc.discovery.ServiceInfoDiscoverer;
import org.hejw.rpc.discovery.ZookeeperServiceInfoDiscoverer;
import org.hejw.rpc.protocol.RpcProtocol;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成代理对象的工厂类
 */
@Getter
@Setter
public class ClientStubProxyFactory {

    //服务发现
    private ServiceInfoDiscoverer serviceInfoDiscovery = new ZookeeperServiceInfoDiscoverer();

    //代理对象缓存，避免每次都新建
    private Map<Class<?>,Object> objectCache = new HashMap<Class<?>,Object>();

    //缓存协议
    HashMap<String, RpcProtocol> supportRpcProtocols = new HashMap<String, RpcProtocol>();

    //通信客户端，用于发送请求
    private NetClient netClient = new NettyClient();

    public <T> T getProxy(Class<T> interf){
        T obj = (T) this.objectCache.get(interf);
        if(obj != null){
            Proxy.newProxyInstance(interf.getClassLoader(),new Class<?> []{interf},
                new ClientStubInvocationHandler(interf.getClass(),serviceInfoDiscovery,netClient));
            this.objectCache.put(interf,obj);
        }
        return obj;
    }


}
